<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never" style="border:0px;">
      <div slot="header" style="font-size:14px;font-weight:bold;">
        <span>还款计划管理</span>
      </div>
    <div class="filter-container" id="searchBox">
      <div class="left">
        <el-form :inline="true" class="demo-form-inline" size="medium" label-position="right" :model="listQuery" ref="listQuery">
          <el-form-item label="姓名：" prop="borrowerName">
            <el-input v-model="listQuery.borrowerName" clearable class="filter-item" placeholder="请输入借款人姓名" />
          </el-form-item>
          <el-form-item label="资方：" prop="capitalId">
            <el-select v-model="listQuery.capitalId" placeholder="请选择" style="min-width:100%;" @change="getList">
              <el-option
                v-for="item in capitals"
                :key="item.id"
                :label="item.capitalName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传状态：" prop="repayPlanUploadStatus">
            <el-select v-model="listQuery.repayPlanUploadStatus" placeholder="请选择" style="min-width:100%;" @change="getList">
              <el-option label="未上传" :value="2"></el-option>
              <el-option label="已上传" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="贷款状态：" prop="LoanStatus">
            <el-select v-model="listQuery.LoanStatus" placeholder="请选择" style="min-width:100%;" @change="getList">
              <el-option
                v-for="item in loanStatusArr"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属机构：" prop="orgId">
            <el-select v-model="listQuery.orgId" placeholder="请选择" style="min-width:100%;" @change="getList">
              <el-option
                v-for="item in allOrgs"
                :key="item.id"
                :label="item.orgName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="right">
        <el-button type="primary"  @click="getList()">查询</el-button>
        <el-button  @click="restForm('listQuery')">重置</el-button>
        <el-button  type="text" @click="closeSearch">{{showOperation}}
          <i :class="[!showAll? 'el-icon-caret-bottom' : 'el-icon-caret-top']"></i>
        </el-button>
      </div>
    </div>

    <vxe-toolbar ref="xToolbar">
         <template #buttons>
         <el-button v-permission="'system:repay-stand-download:access'" type="text" icon="el-icon-download" @click="downloadStand">贷款台账下载</el-button>
        </template>
    </vxe-toolbar>
    <vxe-table
      v-loading="loading"
      :data="taskData"
      border="none"
      highlight-hover-row
      show-header-overflow
      show-overflow
      align="center"
      :header-cell-style="{ background: '#F7F7F8', color: '#606266' }"
      @cell-dblclick="cellDblclick"
    >
      <vxe-table-column type="seq" title="序号" width="50"/>
      <vxe-table-column title="客户姓名" field="borrowerName" width="110"/>
      <vxe-table-column title="身份证" field="borrowerIdCardNo" width="175"/>
      <vxe-table-column title="手机号" field="borrowerPhone" width="130"/>
      <vxe-table-column title="项目名称" field="projectName" width="150"/>
      <vxe-table-column title="所属机构" field="orgName" min-width="150"/>
      <vxe-table-column title="渠道" field="channelName" min-width="110"/>
      <vxe-table-column title="资方" field="capitalName" min-width="120"/>
      <vxe-table-column title="产品" field="productName" min-width="130"/>
      <vxe-table-column title="贷款金额" field="loanAmount" min-width="100"/>
      <vxe-table-column title="贷款期限" field="loanTerm" min-width="100"/>
      <vxe-table-column title="贷款日期" field="loanDate" min-width="100"/>
      <vxe-table-column title="还款方式" field="repayMethodName" min-width="100"/>
      <vxe-table-column title="贷款状态" field="loanStatusName" min-width="100"/>
      <vxe-table-column title="上传状态" field="repayPlanUploadStatusName" min-width="100"/>
      <vxe-table-column title="上传时间" field="repayPlanUploadTime" min-width="120"/>
      <vxe-table-column title="操作" fixed="right" min-width="200">
        <template v-slot="{ row }">
          <span v-if="row.loanStatus != 96">
            <el-button v-if="row.repayPlanUploadStatus === 1" v-permission="'system:upload-repay-plan:access'" type="text" @click="uploadRepayPlanWindow(row)">更新还款计划</el-button>
            <el-button v-if="row.repayPlanUploadStatus === 2" v-permission="'system:upload-repay-plan:access'" type="text" @click="uploadRepayPlanWindow(row)">上传还款计划</el-button>
            <el-divider direction="vertical"></el-divider>
          </span>
          <el-button v-permission="'system:project-repay-manage:access'" type="text" @click="toRepayPlan(row)" v-if="row.repayPlanUploadStatus === 1">还款管理</el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    </el-card>
    <vxe-pager
      class="pager"
      @page-change="changePage"
      :current-page.sync="listQuery.pageNo"
      :page-size.sync="listQuery.pageSize"
      :total="total"
      :page-sizes="[5, 10, 30, 50, 100]"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
    >
    </vxe-pager>

    <el-dialog :title="uploadTitle" :visible.sync="dialogFormVisible" :close-on-click-modal="false" label-width="100px" style="width: 90%; margin-left:50px;">
      <el-upload
        style="margin-top:30px;"
        class="upload-demo"
        ref="upload"
        drag
        name="uploadFile"
        limit="1"
        :headers="headers"
        :data	="dataParam"
        :on-success="handleGalleryUrl"
        :on-change="onChangeFile"
        :on-remove="removeFile"
        :action="uploadRepayPlan"
        :on-exceed="handleExceed"
        :auto-upload="false">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip" style="color: red" v-if="this.isFirstAdd === false">注：更新还款计划后将清空还款记录，请谨慎操作！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer" v-loading="loading">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
      </div>
    </el-dialog>

    <el-dialog title="个金放回款明细下载" :visible.sync="standWindow" :close-on-click-modal="false" v-loading="loading" style="width: 80%">
      <el-form ref="standForm" :model="standForm" status-icon label-position="right" label-width="100px">
        <el-form-item label="截止日期"  :rules="{ required: true, message: '截至日期不能为空', trigger: 'blur' }" prop="loanTime">
          <el-date-picker v-model="standForm.loanTime" clearable type="date" placeholder="请选择截至日期" value-format="yyyy-MM-dd"> </el-date-picker>
        </el-form-item>
        <el-form-item label="所属机构" prop="orgId" :rules="{ required: true, message: '请选择机构', trigger: 'blur' }" >
          <el-select v-model="standForm.orgId" placeholder="请选择" style="min-width:100%;" ref="selectCh">
            <el-option
              v-for="item in allOrgs"
              :key="item.id"
              :label="item.orgName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="width:40%;margin:0 auto;margin-top:30px;">
        <el-button size="small" type="danger" style="width:100px;height:40px;" @click="cancel('standForm')">取消</el-button>
        <el-button type="primary" size="small" style="width:100px;height:40px;" @click="downloadRepayStand('standForm')">下载</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { repayInfoList, listLoanStatus, uploadRepayPlan, downloadRepayStand, addRepayRecord } from '@/api/repayPlan'
import { allOrg} from '@/api/org';
import { allCapitals} from '@/api/capital';
import DicSelect from '@/components/select/index';
import { getToken } from '@/utils/auth'
  import { creditLoanDownload } from '@/api/account'
export default {
  name: 'User',
  components: { DicSelect },
  data: function () {
    return {
      uploadRepayPlan,
      active: 0,
      taskData: [],
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        borrowerName: undefined,
        orgId: undefined,
        capitalId: undefined,
        LoanStatus: undefined,
        repayPlanUploadStatus: undefined,
      },
      allOrgs:[],
      capitals:[],
      isAccessFile:false, // 是否选择文件
      loanStatusArr:[],
      showAll:true,
      dialogFormVisible:false,
      projectId:undefined,
      isFirstAdd:undefined,
      uploadTitle:undefined,
      loading: true,
      standWindow:false,
      standForm:{
        loanTime:undefined,
        orgId:undefined
      },
    };
  },
  computed: {
    headers() {
      return {
        'Authorization': "Bearer-"+getToken()
      }
    },
    dataParam() {
      return {
        'projectId': this.projectId,"isFirstAdd" : this.isFirstAdd
      }
    },
    showOperation: function() {
   if (this.showAll == false) {
    //对文字进行处理
    return "展开";
   } else {
    return "收起";
   }
  }
  },
  mounted(){
  /**
   * 收起搜索
   */
  this.$nextTick(function() {
  //  this.closeSearch();
  });
  },
  created(){
    this.getList();
    this.allOrg();
    this.allCapitals();
    this.listLoanStatus();
  },
  // getTask
  methods: {
    onChangeFile() {
      this.isAccessFile = true;
    },
    removeFile() {
      this.isAccessFile = false;
    },
    submitUpload() {
      if (!this.isAccessFile){
        this.$message.warning(`请先选择文件哦`);
        return false;
      }
      var info = this.isFirstAdd === false ? '此操作将清空原有还款记录，是否继续?' : "确定要导入数据吗？"
      this.$confirm(info, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.upload.submit();
      }).catch(() => {
        this.$message({type: 'info',message: '已取消'});
      });
    },
    handleExceed(files, fileList) {已进件管理

      this.$message.warning(`只能上传1个文件哦`);
    },
    downloadStand() {
      this.standWindow = true;
    },
    cancel(formName) {
      this.standWindow = false;
      this.$refs[formName].resetFields();
    },
    handleGalleryUrl(res, file, fileList) {
      this.loading = true;
      if (res.code === 20000){
        this.$message.success("导入成功")
        this.dialogFormVisible = false;
        this.$refs.upload.clearFiles();
        this.loading = false;
        this.getList()
      }else{
        this.$message.error(res.description)
        this.$refs.upload.clearFiles();
        this.loading = false;
      }
    },
    listLoanStatus() {
      this.loading = true;
      listLoanStatus().then((data) => {
        this.loanStatusArr = data.data
        this.loading = false;
      });
    },
    allOrg() {
      this.loading = true;
      allOrg().then((data) => {
        this.allOrgs = data.data
        this.loading = false;
      });
    },
    allCapitals() {
      this.loading = true;
      allCapitals().then((data) => {
        this.capitals = data.data
        this.loading = false;
      });
    },

    closeSearch() {
   this.showAll = !this.showAll;
   var searchBoxHeght = document.getElementById("searchBox");
   if (this.showAll == false) {
    searchBoxHeght.style.height = 50 + "px";
   } else {
    searchBoxHeght.style.height = "auto";
   }
  },
    // 列表查询
    getList() {
      this.loading = true;
      repayInfoList(this.listQuery).then((data) => {
        this.taskData = data.data;
        this.total = data.total;
        console.log('响应数据:%o', data);
      });
      this.loading = false;
    },
    toRepayPlan(row) {
      this.$router.push({
        path: '/repay/repayPlan',
        query: { parentRepayData: JSON.stringify(row)},
      });
    },
    uploadRepayPlanWindow(row) {
      this.isAccessFile = false;
      this.dialogFormVisible = true;
      this.isFirstAdd = true;
      this.uploadTitle = '上传还款计划';
      if (row.repayPlanUploadStatus === 1){
        this.isFirstAdd = false;
        this.uploadTitle = '更新还款计划';
      }
      this.projectId = row.projectId;
      this.$refs.upload.clearFiles();
    },
    changePage() {
      this.getList();
    },
    restForm(formName) {
      this.$refs[formName].resetFields();
      this.getList();
    },
    cellDblclick({row,rowIndex,column,columnIndex,cell},event) {
      let _this = this;
      this.$copyText(event.target.innerText).then(function() {
        _this.$message.info('复制成功');
      });
    },

    downloadRepayStand(formName) {
      this.loading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          downloadRepayStand(this.standForm).then(res => {
            const blob = new Blob([res]) ;
            var orgName = this.$refs.selectCh.selected.label;
            // // 机构名称+截止时间+借款台账
            const fileName = orgName+this.standForm.loanTime+"借款台账.xlsx"
            // const fileName = "借款台账.xlsx"
            if (window.navigator.msSaveOrOpenBlob) { //兼容IE10
              navigator.msSaveBlob(blob,fileName)
            } else {
              const href = URL.createObjectURL(blob) //创建新的URL表示指定的blob对象
              const a = document.createElement('a') //创建a标签
              a.style.display = 'none'
              a.href = href // 指定下载链接
              a.download = fileName //指定下载文件名
              a.click() //触发下载
              URL.revokeObjectURL(a.href) //释放URL对象
            }
            this.$notify.success({title: '成功',message: '下载成功'})
            this.loading = false;
            this.standWindow = false;
            this.$refs[formName].resetFields();
          }).catch(err => {
            this.$notify.error({title: '失败',message: err.data.message})
          })
        } else {
          this.loading = false
          return false
        }
      })
    }
  },
};
</script>

<style lang="css" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}
.pager{
  position: fixed;
  bottom: 0;
  right: 28px;
  background-color: #FAFAFB;
  z-index: 2;
  height: 40px;
  width: calc(100% - 260px);
  }

.right >>> .el-button--primary,.el-button--default {
  padding: 10px 20px;
}
.vxe-table--render-default >>> .el-button--text{
  color: #2b7bfb;
}
.app-container >>> .vxe-table--render-default,.vxe-pager {
  font-family: PingFangSC, Arial, Helvetica, sans-serif;
}

.left {
  flex: 14;
  display: flex;
  flex-flow: row wrap;
  margin-right: 20px;
}
.left >>> .el-form {
  width: 100%;
}
.left >>> .el-form .el-form-item {
  display: flex;
  flex-flow: row nowrap;
  width: 30%;
  margin-right: 3%;
  float: left;
  margin-bottom: 14px;
}

.left >>> .el-form .el-form-item .el-form-item__label {
  font-weight: 500;
  color: #606266;
  text-align: left;
  /* flex: 1; */
}

.left >>> .el-form .el-form-item .el-form-item__content {
  flex: 1;
  /*超出部分隐藏*/
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
  white-space: nowrap;
  /*规定段落中的文本不进行换行 */
  width: 100%;
}
.date_item {
  width: 100%;
}
.right {
  flex: 2;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-end;
  margin-right: 30px;
  /* margin-bottom: 30px; */
}


</style>
